<?php
if (!defined('BASEPATH'))
	exit ('No direct script access allowed');
class User_token {
	var $CI;
	public function __construct() {
		$this->CI =& get_instance();
	}

	public function check_token() {
		$account_no = $this->CI->Merchant_order->get_account_no();
		$user_token = $this->CI->Merchant_order->get_token();
		if ($user_token =="") {
			return false;
		}
		if ($account_no=="") {
			return false;
		}
		$this->CI->load->library("socket/socket_connect");
		$this->CI->config->load('config_socket');
		$json	=$this->encode_socket_data($account_no);
		$ip 	=$this->CI->config->item('query_ip');
		$port 	=$this->CI->config->item("query_port");
		$length	=$this->CI->config->item("query_length");
		$return =$this->CI->socket_connect->connect(60,$ip,$port,$json,$length);
		$return =substr($return, 10);
		$decode =json_decode($return);
		if ($decode==null) {
			return false;
		}
		if ($decode->CODE!=100) {
			return false;
		}
		return $this->compare_token($decode->UPDATE, $account_no, $_SERVER['REMOTE_ADDR'], $user_token);
	}

	private function encode_socket_data($account_no) {
		$query['CMD']			="QUERY";
		$query['ACCOUNT'] 		=$account_no;
		$json =json_encode($query);
		$length =sprintf("%010d",strlen($json));
		return $length.$json;
	}

	private function compare_token($update,$account_no,$ip,$user_token) {
		$token =base64_encode(md5($ip.$update).$account_no.":".$ip);
		if ($token==$user_token) {
			return true;
		}else{
			return false;
		}
	}
}
